class Member < ActiveRecord::Base
	# Include default devise modules. Others available are:
	# :token_authenticatable, :lockable and :timeoutable
	devise 	:database_authenticatable, :registerable, :recoverable, 
			:rememberable, :trackable, :validatable

	attr_accessible :email, :password, :password_confirmation, :remember_me, 
					:name, :surname, :address, :birthday, :occupation, :about, 
					:city, :nickname, :membership_id, :permission_id, :photo_file_name, 
					:photo_content_type, :photo_file_size, :photo

  has_many :feeds
	has_many :pms
	has_many :sent_pms, :class_name => "Pm", :foreign_key => "from"
	has_many :recieved_pms, :class_name => "Pm", :foreign_key => "to"
	has_many :posts
	has_many :tutorials
	has_many :group_associations, :dependent => :delete_all
	has_many :groups, :through => :group_associations
	has_many :messages
	has_many :thread_visits, :dependent => :delete_all
	
	belongs_to :membership
	belongs_to :permission

	has_attached_file :photo;
	validates_attachment_content_type :photo, :content_type=>['image/jpeg', 'image/png', 'image/gif']
	validates_attachment_size :photo, :less_than=>100.kilobyte

	before_create :default_values
	
	# postavi defaultni membership i permission
	def default_values
		self.membership_id = 4
		self.permission_id = 4
	end

	def age
		return self.birthday
	end

	def has(attribute)
		if self[attribute] != nil then
			return true if self[attribute].length > 0
		end

		return false
	end

	def has_get(attribute)
		if self.has(attribute)
			return self[attribute]
		else
			return ""
		end
	end



	def is_in_group?( group_id )
		return self.groups.exists?( group_id )
	end

	def username
		username = self.email

		if self.name != nil then
			if self.name.length > 0 then
			username = self.name
			end
		end

		if self.nickname != nil then
			if self.nickname.length > 0 then
			username = self.nickname
			end
		end

		return username
	end

	def full_name
		name = self.has_get(:name) +" "+ self.has_get(:surname)

		if name.length > 1
			name += " (" + self.email + ")"
		else
		name = self.email
		end

		if self.has(:nickname)
			name += " a.k.a. " + self.nickname
		end

		return name
	end

	# provjera odobrenosti
	def is_approved?

		if self.permission.id <= 3
		return true
		else
		return false
		end

	end

	# provjera mod ovlasti
	def is_moderator?

		if( self.permission.id <= 2)
		return true
		else
		return false
		end

	end

	def is_admin?

		if( self.permission.id == 1)
		return true
		else
		return false
		end

	end

	def is_admin_or_this_member?( member )

		return true if self.is_admin?
		return true if self.id == member.id
		return false

	end

	def is_moderator_or_this_member?( member )

		return true if self.is_moderator?
		return true if self.id == member.id
		return false

	end
	
	def count_unread_pms
		return self.recieved_pms.where('`read` = 0').count
	end

end
